﻿using Core.Framework.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Linq;

namespace Core.Web
{
    /// <summary>
    /// API数据处理
    /// </summary>
    public class ApiBaseControllerAttribute : Attribute, IActionFilter
    {

        /// <summary>
        /// Action执行前
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
        }

        /// <summary>
        /// Action执行完成后
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {

            bool isApiVerification = context.Filters.Any(a => a is ApiVerificationAttribute);

            if (!isApiVerification)
            {
                this.ResultEncrypt(context);
            }
            

        }


        /// <summary>
        /// 返回数据加密
        /// </summary>
        /// <param name="context"></param>
        public void ResultEncrypt(ActionExecutedContext context)
        {

            // 支付宝 加密有问题
            return;

            if (context.HttpContext.Items.ContainsKey("EncryptKey"))
            {
                // 获取密钥
                var encryptKey = context.HttpContext.Items["EncryptKey"].ToString();


                // 返回信息
                object result;

                bool isJsonResult = context.Result.GetType() == typeof(JsonResult);

                if (isJsonResult)
                    result = ((JsonResult)context.Result).Value;
                else
                    result = (IResult)((ObjectResult)context.Result).Value;

                var json = JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings
                {
                    ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
                    DateFormatString = "yyyy-MM-dd HH:mm:ss"
                });

                // 有过存在密钥则加密返回数据
                if (!string.IsNullOrWhiteSpace(encryptKey) && json.Length < 600)
                    {
                    context.HttpContext.Response.Headers["Encrypt"] = "true";

                    if (isJsonResult)
                        ((JsonResult)context.Result).Value = AESEncrypt.Encrypt(json, encryptKey);
                    else
                    {
                        ((ObjectResult)context.Result).Value = AESEncrypt.Encrypt(json, encryptKey);
                    }

                }
            
            }
        }


    }
}
